package com.example.mywike.user.controller;

import com.example.mywike.config.shiroConfig.ShiroConfigStingInteger;
import com.example.mywike.user.AaEntity;
import com.example.mywike.user.TestMapper;
import com.example.mywike.user.entity.inputEntity.UserLoginInput;
import com.example.mywike.user.service.UserLoginService;
import com.example.mywike.utils.returnUtils.ReturnData;
import com.example.mywike.utils.returnUtils.ReturnUtils;
import org.apache.catalina.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private TestMapper testMapper;

    @Autowired
    private UserLoginService userLoginService;

    @PostMapping("/getPassword")
    public ReturnData te(@RequestBody UserLoginInput userLoginInput) {
        String newPwd= new SimpleHash(ShiroConfigStingInteger.ALGORITHM_MD5,userLoginInput.getCredential(),
                userLoginInput.getIdentifier(), ShiroConfigStingInteger.TIMES_1).toHex();
        System.out.println("newPwd = " + newPwd);
        return ReturnUtils.success(newPwd);
    }




    @PostMapping("/login")
    public ReturnData login(@RequestBody UserLoginInput userLoginInput) {
        ReturnData returnData = userLoginService.login(userLoginInput);
        return returnData;
    }

    @RequestMapping("/loginUser")
    public ReturnData loginUser(String identifier, String credential, String identifierType) {
        //1.获取Subject对象
        Subject subject = SecurityUtils.getSubject();
        //2.通过Subject提交用户信息,交给shiro框架进行认证操作
        //2.1对用户进行封装
        String username = identifier + ShiroConfigStingInteger.DELIMITER + identifierType;
        UsernamePasswordToken userToken = new UsernamePasswordToken(username, credential);
        //2.2对用户信息进行身份认证
        subject.login(userToken);
        //分析:
        //1)token会传给shiro的SecurityManager
        //2)SecurityManager将token传递给认证管理器
        //3)认证管理器会将token传递给realm

        return ReturnUtils.success(userToken);
    }

    @RequestMapping("/logout")
    public ReturnData logOut(HttpSession session) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
//        session.removeAttribute("user");
        return ReturnUtils.success();

    }



    @PostMapping("/home")
    public ReturnData home(){
        return ReturnUtils.success("hello world!");
    }

    @GetMapping("/home1")
    public ReturnData home1(){
        return ReturnUtils.success("hello world!");
    }

}
